package com.cap.dreamcircle.View;

import android.content.Intent;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Base.BaseActivity;
import com.cap.dreamcircle.Consts.Constants;
import com.cap.dreamcircle.Model.Action.CommentsAction;
import com.cap.dreamcircle.Model.Bean.BaseBean;
import com.cap.dreamcircle.Model.Bean.CommentEntity;
import com.cap.dreamcircle.Model.Bean.DreamDetailBean;
import com.cap.dreamcircle.Model.IDreamModel;
import com.cap.dreamcircle.Model.Impl.DreamModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.CommonSubscriber;
import com.cap.dreamcircle.Utils.DisplayUtil;
import com.cap.dreamcircle.Utils.GlideUtils;
import com.cap.dreamcircle.Utils.KeyboardUtils;
import com.cap.dreamcircle.Utils.MD5Utils;
import com.cap.dreamcircle.Utils.PreferenceUtils;
import com.cap.dreamcircle.Utils.ShareDialogUtils;
import com.cap.dreamcircle.Utils.SimpleMediaPlayerUtils;
import com.cap.dreamcircle.Utils.TimeUtils;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.cap.dreamcircle.Utils.TransformUtils;
import com.cap.dreamcircle.View.Adapter.AdapterDreamDetailsComments;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Subscriber;
import rx.functions.Action0;

/**
 * Created by liucxu on 2017/6/22.
 */

public class DreamDetailActivity extends BaseActivity {

    @BindView(R.id.layout_back)
    LinearLayout layout_back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipe_refresh_layout;
    @BindView(R.id.list_view_comments)
    ListView list_view_comments;
    @BindView(R.id.imv_post_comment)
    ImageView imv_post_comment;
    @BindView(R.id.edt_post_comment)
    EditText edt_post_comment;
    @BindView(R.id.layout_post_comments)
    RelativeLayout layout_post_comments;
    @BindView(R.id.layout_body)
    RelativeLayout layout_body;
    @BindView(R.id.check_anonymous)
    CheckBox check_anonymous;

    private View header_view;

    private AdapterDreamDetailsComments adapter;

    private IDreamModel model;
    private String dreamId;

    private CircleImageView circle_header_imv;
    private TextView tv_friend_dream_time;
    private TextView tv_user_name;
    private TextView tv_dreams_details;
    private ImageView imv_dream_delete;
    private ImageView imv_dream_like;
    private ImageView imv_dream_comment;
    private RelativeLayout layout_audio;
    private ImageView imv_playing_status_audio;
    private TextView tv_length_audio;
    private TextView tv_like_num;
    private TextView tv_comment_num;
    private ImageView imv_dream_solve;
    private ImageView imv_dream_share;

    private String toUserId = "";
    private String toCommentId = "";
    private List<CommentEntity> entities = new ArrayList<>();
    private int currentKeyboardH;

    @Override
    public int getLayoutId() {
        return R.layout.activity_dream_details;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        adapter = new AdapterDreamDetailsComments(this, new ArrayList<CommentEntity>());
        list_view_comments.setAdapter(adapter);
        header_view = View.inflate(this, R.layout.header_deam_details, null);
        if (list_view_comments.getHeaderViewsCount() == 0) {
            list_view_comments.addHeaderView(header_view);
        }
        dreamId = getIntent().getStringExtra("dreamId");
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                App.GetInstance().finishActivity(DreamDetailActivity.this);
            }
        });
        if (TextUtils.isEmpty(dreamId)) {
            App.GetInstance().finishActivity(DreamDetailActivity.this);
        }
        tv_like_num = (TextView) header_view.findViewById(R.id.tv_like_num);
        tv_comment_num = (TextView) header_view.findViewById(R.id.tv_comment_num);
        circle_header_imv = (CircleImageView) header_view.findViewById(R.id.circle_header_imv);
        tv_friend_dream_time = (TextView) header_view.findViewById(R.id.tv_friend_dream_time);
        tv_user_name = (TextView) header_view.findViewById(R.id.tv_user_name);
        tv_dreams_details = (TextView) header_view.findViewById(R.id.tv_dreams_details);
        imv_dream_delete = (ImageView) header_view.findViewById(R.id.imv_dream_delete);
        imv_dream_like = (ImageView) header_view.findViewById(R.id.imv_dream_like);
        imv_dream_comment = (ImageView) header_view.findViewById(R.id.imv_dream_comment);
        imv_dream_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toUserId = "";
                toCommentId = "";
                edt_post_comment.setHint("回复梦境");
                updateEditTextBodyVisible(View.VISIBLE);
            }
        });
        layout_audio = (RelativeLayout) header_view.findViewById(R.id.layout_audio);
        imv_playing_status_audio = (ImageView) header_view.findViewById(R.id.imv_playing_status_audio);
        tv_length_audio = (TextView) header_view.findViewById(R.id.tv_length_audio);
        imv_dream_solve = (ImageView) header_view.findViewById(R.id.imv_dream_solve);
        imv_dream_share = (ImageView) header_view.findViewById(R.id.imv_dream_share);
        imv_post_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edt_post_comment.getText().toString().trim())) {
                    ToastUtils.showShortToast(DreamDetailActivity.this, "请输入评论内容");
                } else {
                    postComment();
                }
            }
        });
        swipe_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDreamDetails();
            }
        });
        list_view_comments.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (edt_post_comment.getVisibility() == View.VISIBLE) {
                    updateEditTextBodyVisible(View.GONE);
                    return false;
                }
                return false;
            }
        });
        list_view_comments.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (entities.size() > 0) {
                    String local_toUser_id = entities.get(position).getUserId();
                    toCommentId = entities.get(position).getCommentId();
                    if (!PreferenceUtils.GetUserId().equals(local_toUser_id)) {
                        toUserId = local_toUser_id;
                        edt_post_comment.setHint("回复" + entities.get(position).getNickName());
                    }
                }
            }
        });
        setViewTreeObserver();
    }

    public void updateEditTextBodyVisible(int visibility) {
        edt_post_comment.setText("");
//        layout_post_comments.setVisibility(visibility);
        if (View.VISIBLE == visibility) {
            edt_post_comment.requestFocus();
            //弹出键盘
            KeyboardUtils.showSoftInput(edt_post_comment.getContext(), edt_post_comment);
        } else if (View.GONE == visibility) {
            //隐藏键盘
            KeyboardUtils.hideSoftInput(edt_post_comment.getContext(), edt_post_comment);
        }
    }

    private void postComment() {
        model.PostDreamComment(edt_post_comment.getText().toString(), dreamId, toUserId, toCommentId, check_anonymous.isChecked()).compose(TransformUtils.<BaseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                edt_post_comment.setText("");
                getDreamDetails();
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.showShortToast(DreamDetailActivity.this, response.getDesc());
            }
        });
    }

    @Override
    public void setupData() {
        model = new DreamModelImpl();
    }

    private void getDreamDetails() {
        model.DreamRecordDetail(dreamId).compose(TransformUtils.<DreamDetailBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<DreamDetailBean>() {
            @Override
            public void onSuccess(DreamDetailBean response) {
                swipe_refresh_layout.setRefreshing(false);
                hideProgress();
                initViewsWithData(response);
            }

            @Override
            public void onFailure(BaseBean response) {
                swipe_refresh_layout.setRefreshing(false);
                hideProgress();
                ToastUtils.showShortToast(DreamDetailActivity.this, response.getDesc());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getDreamDetails();
    }

    private void initViewsWithData(final DreamDetailBean response) {
        tv_friend_dream_time.setText(TimeUtils.formatTime(response.getCreateTime()));
        if (TextUtils.isEmpty(response.getDreamText())) {
            tv_dreams_details.setVisibility(View.GONE);
        } else {
            tv_dreams_details.setVisibility(View.VISIBLE);
            tv_dreams_details.setText(response.getDreamText());
        }
        if (TextUtils.isEmpty(response.getDreamVoiceUrl())) {
            layout_audio.setVisibility(View.GONE);
        } else {
            layout_audio.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(layout_audio.getLayoutParams());
            layoutParams.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
            int min_width = DisplayUtil.dip2px(App.GetInstance(), 128);
            int max_width = DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(App.GetInstance(), 36);
            int width = min_width + ((int) (response.getAudio_length() * (max_width - min_width) / 180));
            layout_audio.getLayoutParams().width = width;
            layout_audio.requestLayout();
            tv_length_audio.setText(response.getAudio_length() + "'");

            imv_playing_status_audio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SimpleMediaPlayerUtils.getInstance(DreamDetailActivity.this).play(Constants.BASE_URL + response.getDreamVoiceUrl(), new SimpleMediaPlayerUtils.VoicePlayInterface() {
                        @Override
                        public void onStartPlaying() {
                            imv_playing_status_audio.setImageResource(0);
                            imv_playing_status_audio.setImageDrawable(null);
                            imv_playing_status_audio.setImageURI(null);
                            imv_playing_status_audio.setImageResource(R.mipmap.audio_playing);
                        }

                        @Override
                        public void onPause() {
                            imv_playing_status_audio.setImageResource(0);
                            imv_playing_status_audio.setImageDrawable(null);
                            imv_playing_status_audio.setImageURI(null);
                            imv_playing_status_audio.setImageResource(R.mipmap.audio_pause);
                        }

                        @Override
                        public void onPlayCompleted() {
                            imv_playing_status_audio.setImageResource(0);
                            imv_playing_status_audio.setImageDrawable(null);
                            imv_playing_status_audio.setImageURI(null);
                            imv_playing_status_audio.setImageResource(R.mipmap.audio_pause);
                        }
                    });
                }
            });
        }
        adapter.setDatas(response.getCommentArray());
        entities.clear();
        entities.addAll(response.getCommentArray());
        GlideUtils.getInstance().LoadContextBitmap(this, Constants.BASE_URL + response.getHeadImgUrl(), circle_header_imv, R.mipmap.default_header, R.mipmap.default_header, GlideUtils.LOAD_BITMAP);
        tv_user_name.setText(response.getNickName());
        if (response.isMyRecord()) {
            imv_dream_delete.setVisibility(View.VISIBLE);
            imv_dream_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDelete(response.getDreamId());
                }
            });
            imv_dream_solve.setVisibility(View.VISIBLE);
            imv_dream_share.setVisibility(View.VISIBLE);
            imv_dream_solve.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(DreamDetailActivity.this, SolveDreamActivity.class);
                    intent.putExtra("dreamDetail", response.getDreamText());
                    intent.putExtra("dreamTime", response.getCreateTime());
                    intent.putExtra("dreamVoiceUrl", response.getDreamVoiceUrl());
                    intent.putExtra("dreamId", response.getDreamId());
                    startActivity(intent);
                }
            });
            imv_dream_share.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String url = "http://app.5idreamer.com:8080/dream/" + "dream.do?task=shareDream&" + "dreamId=" + dreamId + "&validCode=" + MD5Utils.GetMD5Value(dreamId + "dreamio");
                    ShareDialogUtils.init().share(DreamDetailActivity.this, url);
                }
            });
        } else {
            imv_dream_delete.setVisibility(View.INVISIBLE);
            imv_dream_solve.setVisibility(View.GONE);
            imv_dream_share.setVisibility(View.GONE);
        }
        if (response.isLiked()) {
            imv_dream_like.setImageResource(R.mipmap.imv_dream_liked);
            imv_dream_like.setEnabled(false);
        } else {
            imv_dream_like.setEnabled(true);
            imv_dream_like.setImageResource(R.mipmap.imv_dream_like);
            imv_dream_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    likeDreamCircle(response.getDreamId());
                }
            });
        }
        if (response.getLikeCount() == 0) {
            tv_like_num.setVisibility(View.GONE);
        } else {
            tv_like_num.setVisibility(View.VISIBLE);
            tv_like_num.setText(response.getLikeCount() + "");
        }
        if (response.getCommentCount() == 0) {
            tv_comment_num.setVisibility(View.GONE);
        } else {
            tv_comment_num.setVisibility(View.VISIBLE);
            tv_comment_num.setText(response.getCommentCount() + "");
        }
    }

    private void showDelete(final String dreamId) {
        MaterialDialog dialog = new MaterialDialog.Builder(this).title("提示").content("确定删除?").positiveText("确定").negativeText("取消").onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                DeleteDreamCircleById(dreamId);
            }
        }).build();
        dialog.show();
    }

    private void DeleteDreamCircleById(String id) {
        model.DeleteDreamCircleById(id).compose(TransformUtils.<BaseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new Subscriber<BaseBean>() {
            @Override
            public void onCompleted() {
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                hideProgress();
            }

            @Override
            public void onNext(BaseBean response) {
                hideProgress();
                if (response.getCode() == 0) {
                    App.GetInstance().finishActivity(DreamDetailActivity.this);
                } else {
                    ToastUtils.showShortToast(DreamDetailActivity.this, response.getDesc());
                }
            }
        });
    }

    private void likeDreamCircle(String dreamId) {
        model.LikeDreamCircleRecord(dreamId).compose(TransformUtils.<BaseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new Subscriber<BaseBean>() {
            @Override
            public void onCompleted() {
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                hideProgress();
            }

            @Override
            public void onNext(BaseBean res) {
                hideProgress();
                if (res.getCode() == 0) {
                    getDreamDetails();
                } else {
                    ToastUtils.showShortToast(DreamDetailActivity.this, res.getDesc());
                }
            }
        });
    }

    public void onEvent(CommentsAction action) {
//        if (action != null && !TextUtils.isEmpty(action.getToUserId())&&!PreferenceUtils.GetUserId().equals(action.getToUserId())) {
        toUserId = action.getToUserId();
        toCommentId = entities.get(action.getPosition()).getCommentId();
        edt_post_comment.setHint("回复" + entities.get(action.getPosition()).getNickName());
        updateEditTextBodyVisible(View.VISIBLE);
//        }
    }

    private void setViewTreeObserver() {
        final ViewTreeObserver swipeRefreshLayoutVTO = layout_body.getViewTreeObserver();
        swipeRefreshLayoutVTO.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                layout_body.getWindowVisibleDisplayFrame(r);
                int statusBarH = getStatusBarHeight();//状态栏高度
                int screenH = layout_body.getRootView().getHeight();
                if (r.top != statusBarH) {
                    //在这个demo中r.top代表的是状态栏高度，在沉浸式状态栏时r.top＝0，通过getStatusBarHeight获取状态栏高度
                    r.top = statusBarH;
                }
                int keyboardH = screenH - (r.bottom - r.top);
                if (keyboardH == currentKeyboardH) {//有变化时才处理，否则会陷入死循环
                    return;
                }
                currentKeyboardH = keyboardH;
                if (keyboardH < 150) {//说明是隐藏键盘的情况
                    updateEditTextBodyVisible(View.GONE);
                    return;
                }
            }
        });
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
